const JSONEditor = require('agency4api/dist/jsoneditor/jsoneditor.min.js')

try {
    import('agency4api/dist/jsoneditor/jsoneditor.min.css')
} catch {
    require('agency4api/dist/jsoneditor/jsoneditor.min.css')
}

window.agency4api = {}

let thisJSONEditor = null

let oMainWrap = null
const ajax = function (_json, isAsync = true) {
    const json = _json || {}
    if (!json.url) {
        throw new Error('没有输入地址')
    }
    const ajaxType = json.type || 'get'
    json.timeout = json.timeout || 10000
    json.data = json.data || {}

    const oAjax = new XMLHttpRequest()

    // agency4api的实例添加到下拉框
    if (oMainWrap) {
        const agency4apiList = (window.localStorage.agency4apiList || '').split(',')
        const oDom = oMainWrap.querySelector('.j-instance-group')
        const index = agency4apiList.findIndex(item => item === oDom.value)
        if (index > 0) {
            let optionsStr = ''
            agency4apiList.unshift(agency4apiList.splice(index, 1)[0])
            agency4apiList.forEach(item => {
                optionsStr += `<option value="${ item }">${ item }</option>`
            })
            oDom.innerHTML = optionsStr

            window.localStorage.agency4apiList = agency4apiList.join(',')
        }
    }

    switch (ajaxType.toUpperCase()) {
        case 'GET':
            oAjax.open('GET', `${ json.url }?${ json2url(json.data) }`, isAsync)
            oAjax.send()
            break
        case 'POST':
            oAjax.open('POST', json.url, isAsync)
            const contentType = json.contentType || 'application/json'
            oAjax.setRequestHeader('Content-Type', contentType)
            let param = null
            switch (contentType) {
                case 'application/json':
                    param = JSON.stringify(json.data)
                    break
                case 'application/x-www-form-urlencoded':
                    param = json2url(json.data)
                    break
            }
            oAjax.send(param)
            break
    }

    oAjax.onreadystatechange = function () {
        if (oAjax.readyState === 4) {
            clearTimeout(timer)
            if (oAjax.status >= 200 && oAjax.status < 300 || oAjax.status === 304) {
                json.success && json.success(oAjax.responseText ? JSON.parse(oAjax.responseText) : '')
            } else {
                json.error && json.error(oAjax.status)
            }
        }
    }
    let timer = setTimeout(() => {
        oAjax.onreadystatechange = null
        json.error && json.error('网络超时')
    }, json.timeout)
}
let json2url = function (json) {
    const arr = []
    for (const name in json) {
        arr.push(`${ name }=${ json[name] }`)
    }
    return arr.join('&')
}

if (window.localStorage.agency4apiInserted !== 'true') {
    ajax({
        data: { t: Date.now() },
        url: '/insert-agency4api',
        success(data) {
            Object.keys(data).forEach(attr => {
                window.localStorage[attr] = data[attr]
            })
        },
    })
}

const hideDom = function (dom) {
    dom.style.display = 'none'
}
const showDom = function (dom) {
    dom.style.display = 'block'
}
// 为了不影响主程序，使用异步
const fn = function () {
    if (window.localStorage.agency4apiInserted !== 'true') {
        return
    }
    const htmlText = `
    <div class="agency4api-mask"></div>
    <div class="agency4api-wrap">
        <span e-type="close" class="agency4api-close">X</span>
        <select class="j-instance-group">
        </select> <span class="agency4api-message-info j-agency4api-message-info"></span><br>
        <input type="text" class="agency-key agency-mt10 j-agency-key" placeholder="请输入关键值；回车查询；alt + 回车删除" />
        <input type="number" min="0" class="set-delay j-set-delay" placeholder="设置延时(s)" />
        <br>
        <select class="agency-mt10 j-apiStatus">
        </select>
        <select class="j-agency-path-group">
        </select>
        <input type="file" class="agency-file j-agency-file"/>
        <div class="params-wrap">
            <textarea class="text-area agency-mt10 j-agency-query-param" placeholder="url参数(非必填)"></textarea>
            <textarea class="text-area agency-mt10 j-agency-param-param" placeholder="post参数(application/json,非必填)"></textarea>
        </div>
        <br>
        <div class="text-area result j-agency-area-wrap"></div>
        <br>
        <div class="flex j-normal-btn">
            <div class="flex-item">
                <button e-type="query">查询</button>
                <button e-type="recycle">回收</button>
                <button e-type="query-config" title="alt + 单点 => 修改config">config</button>
                <button e-type="delete">删除</button>
            </div>
            <div class="flex-item">
                <button class="ard" e-type="start">开关</button>
                <button e-type="insert">新增</button>
                <button e-type="edit" title="alt + 回车">修改</button>
                <button class="ard" e-type="refresh" title="alt + 双击">自新</button>
            </div>
        </div>
        <div class="flex j-sure-delete" style="display: none;">
            <div class="flex-item" style="width: 100%">
                <span class="box4delete j-box4delete">
                    <label><input name="del" type="radio" class="j-del-by-url" /> aip删除</label>
                    <label><input name="del" type="radio" class="j-del-by-group" /> group删除</label>
                    <label><input name="del" type="radio" class="j-clear" /> 清空</label>
                    <label><input name="del" type="radio" class="j-clearAll" /> 全部清除</label>
                </span>
                <button e-type="cancel-delete">取消</button>
                <button class="ard" e-type="sure-delete">确定删除</button>
            </div>
        </div>
    </div>
    <div class="agency4api-tip j-auto">
    </div>
    <div class="agency4api-tip left j-fresh">
    </div>
    <style>
    @keyframes agency4api-error-tip {
        20% {
            background: red;
            color: white;
        }
        100% {
            background: red;
            color: white;
        }
    }
    @keyframes agency4api-success-tip {
        20% {
            background: green;
            color: white;
        }
        100% {
            background: red;
            color: white;
        }
    }
    .agency4api-mask{
        display: none;
        position: fixed;
        left: 0;
        top: 0;
        height: 100%;
        width: 100%;
        z-index: 100000;
        background: rgba(0,0,0,0.2);
    }
    .agency4api-wrap {
        display: none;
        position: fixed;
        left: 50%;
        top: 0;
        font-size: 16px;
        z-index: 100001;
        transform: translate(-50%, 0);
        margin: 10px auto;
        width: 60%;
        background: white;
        border: 1px solid gray;
        padding: 20px;
    }

    .agency4api-wrap .agency4api-close{
        position: absolute;
        z-index: 1;
        right: 10px;
        top: 10px;
        font-size: 30px;
        cursor: pointer;
    }

    .agency4api-wrap .agency4api-message-info{
        display: inline-block;
        padding: 0 20px;
        margin: 0 50px;
        line-height: 30px;
    }

    .agency4api-wrap .agency-data-error{
        animation: agency4api-error-tip 1s linear 0s 1;
    }

    .agency4api-wrap .agency-data-success{
        animation: agency4api-success-tip 1s linear 0s 1;
    }

    .agency4api-wrap .agency-mt10{
        margin-top: 10px;
    }
    .agency4api-wrap input,.agency4api-wrap select{
        box-sizing: border-box;
        padding: 0 10px;
        height: 32px;
    }
    .agency4api-wrap .agency-file{
        cursor: pointer; 
        vertical-align: middle;
    }
    .agency4api-wrap .params-wrap{
        display: flex;
    }
    .agency4api-wrap .ard{
        color: green;
    }
    .agency4api-wrap .agency-key{
        width: 80%;
    }
    .agency4api-wrap .set-delay{
        width: 15%;
    }
    .agency4api-wrap .text-area{
        height: 15vh;
        width: 100%;
        box-sizing: border-box;
    }
    .agency4api-wrap .text-area.result{
        height: 50vh;
    }

    .agency4api-wrap .box4delete{
        display: none;
    }
    .agency4api-wrap .box4delete label{
        cursor: pointer;
    }

    .agency4api-wrap .flex {
        display: flex;
    }

    .agency4api-wrap textarea,
    .agency4api-wrap input {
        border: 1px solid gray;
    }

    .agency4api-wrap .flex-item {
        width: 49%;
    }

    .agency4api-wrap .flex-item:last-child {
        flex: 1;
        text-align: right;
    }

    .agency4api-wrap .flex-item button {
        cursor: pointer;
        height: 4vh;
        width: 22%;
    }

    .agency4api-tip{
        position: fixed;
        right: 10px;
        top: 0;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 45%;
        color: green;
        font-size: 16px;
        z-index: 1000;
        cursor: pointer;
    }
    .agency4api-tip span{
        margin-left: 5px;
    }
    .agency4api-tip.left{
        right: auto;
        left: 10px;
    }
    .agency4api-tip.bottom{
        top: auto;
        bottom: 10px;
    }
    </style>
    `
    const oDiv = document.createElement('div')
    oDiv.innerHTML = htmlText
    const oMask = oDiv.children[0]
    oMainWrap = oDiv.children[1]
    const keyDom = oMainWrap.querySelector('.j-agency-key')
    const oDeleteBox = oMainWrap.querySelector('.j-box4delete')
    const oNormalBtnWrap = oMainWrap.querySelector('.j-normal-btn')
    const oSureDelWrap = oMainWrap.querySelector('.j-sure-delete')
    const oMessageInfo = oMainWrap.querySelector('.j-agency4api-message-info')

    let isTipStartBottom = window.localStorage.isAgency4apiTipBottom === 'true'
    let isTipRefreshBottom = window.localStorage.isAgency4apiRefreshTipBottom === 'true'

    const oAutoWrap = oDiv.querySelector('.j-auto')
    const autoAgencyList = JSON.parse(window.localStorage.autoAgencyList || '{}')
    let title = ''
    Object.keys(autoAgencyList).forEach(attr => {
        const str = attr.replace('/', '')
        const target = autoAgencyList[attr] ? str : ''
        oAutoWrap.innerHTML += `<span class="j-auto-${ str }">${
            target
        }</span>`
        title += ` ${ target }`
    })
    oAutoWrap.title = title

    const oAutoRefresh = oDiv.querySelector('.j-fresh')
    const autoRefreshList = JSON.parse(window.localStorage.autoRefreshList || '{}')
    title = ''
    Object.keys(autoRefreshList).forEach(attr => {
        const str = attr.replace('/', '')
        const target = autoRefreshList[attr] ? str : ''
        oAutoRefresh.innerHTML += `<span class="j-refresh-${ str }">${
            target
        }</span>`
        title += ` ${ target }`
    })
    oAutoRefresh.title = title

    if (isTipStartBottom) {
        oAutoWrap.classList.add('bottom')
    }
    if (isTipRefreshBottom) {
        oAutoRefresh.classList.add('bottom')
    }

    const showSuccessTip = (info) => {
        oMessageInfo.innerText = info
        console.log(info)
        oMessageInfo.classList.add('agency-data-success')
        oMessageInfo.timer = setTimeout(() => {
            oMessageInfo.classList.remove('agency-data-success')
            oMessageInfo.innerText = ''
        }, 1000)
    }
    const showErrorTip = (info) => {
        oMessageInfo.innerText = info
        console.log(info)
        oMessageInfo.classList.add('agency-data-error')
        oMessageInfo.timer = setTimeout(() => {
            oMessageInfo.classList.remove('agency-data-error')
            oMessageInfo.innerText = ''
        }, 1000)
    }

    oAutoWrap.onclick = function () {
        let action = null
        if (isTipStartBottom) {
            action = 'remove'
        } else {
            action = 'add'
        }
        this.classList[action]('bottom')

        window.localStorage.isAgency4apiTipBottom = isTipStartBottom = !isTipStartBottom
    }
    oAutoRefresh.onclick = function () {
        let action = null
        if (isTipRefreshBottom) {
            action = 'remove'
        } else {
            action = 'add'
        }
        this.classList[action]('bottom')

        window.localStorage.isAgency4apiRefreshTipBottom = isTipRefreshBottom = !isTipRefreshBottom
    }

    while (oDiv.children.length) {
        document.body.appendChild(oDiv.children[0])
    }

    const agency4apiList = (window.localStorage.agency4apiList || '').split(',')
    // agency4api的实例添加到下拉框
    {
        const oDom = oMainWrap.querySelector('.j-instance-group')
        let optionsStr = ''
        agency4apiList.forEach(item => {
            optionsStr += `<option value="${ item }">${ item }</option>`
        })
        oDom.innerHTML = optionsStr
    }

    {
        // agency4api的apiStatus
        const oDom = oMainWrap.querySelector('.j-apiStatus')
        let optionsStr = '';
        (window.localStorage.apiStatus || '').split(',').forEach(item => {
            optionsStr += `<option value="${ item }">${ item }</option>`
        })
        optionsStr += '<option value="onlyadd">只添加</option><option value="">delete</option>'
        oDom.innerHTML = optionsStr
    }

    // agency4api 选择文件
    oMainWrap.querySelector('.j-agency-file').onchange = (e) => {
        if (e.target.files.length) {
            const file = e.target.files[0]
            const reader = new FileReader()
            reader.onload = () => {
                const array = Array.prototype.slice.call(new Uint8Array(reader.result))
                thisJSONEditor.setText(JSON.stringify(array))
            }
            reader.readAsArrayBuffer(file)
        }
    }

    {
        const initPathGroups = (agency4api) => {
            // agency4api 的 path-group
            const oDom = oMainWrap.querySelector('.j-agency-path-group')
            let optionsStr = ''
            Object.keys(JSON.parse(window.localStorage.pathGroupsList)[agency4api]).forEach(item => {
                optionsStr += `<option value="${ item }">${ item }</option>`
            })
            oDom.innerHTML = optionsStr
        }

        initPathGroups(agency4apiList[0])

        oMainWrap.querySelector('.j-instance-group').onchange = (e) => {
            initPathGroups(e.target.value)
        }
    }

    let isFirst = true
    const onContextmenu = (e) => {
        if (e.altKey) {
            e.preventDefault()
            showDom(oMask)
            showDom(oMainWrap)
            
            if (isFirst) {
                const agencyAreaWrap = document.querySelector('.j-agency-area-wrap')
                thisJSONEditor = new JSONEditor(agencyAreaWrap, {
                    search: true,
                    enableSort: false,
                    enableTransform: false,
                    indentation: 4,
                    modes: ['code', 'form', 'text'],
                })

                agencyAreaWrap.onkeypress = function (e) {
                    if (e.altKey && e.keyCode === 13) {
                        oMainWrap.onclick({
                            target: oMainWrap.querySelector('[e-type="edit"]'),
                        })
                    }
                }

                thisJSONEditor.setText('{}')
            }

            if (isFirst) {
                isFirst = false
            }

            document.dispatchEvent(new Event('agency4api-show'))
        }
    }
    document.addEventListener('contextmenu', onContextmenu)
    document.addEventListener('touchend', onContextmenu)
    oMask.onclick = function () {
        [oMask, oMainWrap, oDeleteBox, oSureDelWrap].forEach(item => hideDom(item))

        oNormalBtnWrap.style.display = 'flex'

        document.dispatchEvent(new Event('agency4api-hide'))
    }

    keyDom.onkeypress = function (e) {
        if (e.keyCode === 13) {
            let targetBtn = null
            if (e.altKey) { // alt + 回车 =》 删除key对应的api
                [...oDeleteBox.querySelectorAll('input')].forEach(dom => {
                    dom.checked = false
                })

                targetBtn = oMainWrap.querySelector('[e-type="sure-delete"]')
            } else { // 回车查询
                targetBtn = oMainWrap.querySelector('[e-type="query"]')
            }
            oMainWrap.onclick({
                target: targetBtn,
            })
        }
    }

    window.agency4api.show = (targetData) => {
        const delayDom = oMainWrap.querySelector('.j-set-delay')
        let value = '{}'
        let query = ''
        let param = ''
        let extname = ''
        extname = targetData.extname
        value = JSON.stringify(JSON.parse(targetData.data), null, extname === 'json' ? 2 : 0)

        query = Object.keys(targetData.query || {}).length ? JSON.stringify(targetData.query, null, 2) : ''
        param = targetData.param ? JSON.stringify(JSON.parse(targetData.param), null, 2) : ''
        targetData.store && (delayDom.value = targetData.store.delay)

        oMainWrap.querySelector('.j-agency-query-param').value = query
        oMainWrap.querySelector('.j-agency-param-param').value = param

        if (thisJSONEditor) {
            thisJSONEditor.setText(value)
        }
    }

    oMainWrap.querySelector('.j-set-delay').onkeypress = function (e) {
        if (e.keyCode === 13) {
            oMainWrap.onclick({
                target: oMainWrap.querySelector('[e-type="edit"]'),
            })
        }
    }

    oMainWrap.ondblclick = function (e) {
        if (e.altKey) {
            oMainWrap.onclick({
                target: oMainWrap.querySelector('[e-type="refresh"]'),
            })
        }
    }

    oMainWrap.onclick = function (e) {
        const eType = e.target.getAttribute('e-type')
        let val = oMainWrap.querySelector('.j-instance-group').value
        const delayDom = oMainWrap.querySelector('.j-set-delay')
        const delay = delayDom.value.trim()

        switch (eType) {
            case 'start': {
                ajax({
                    url: `${ val }/agency-change-agency`,
                    success(data) {
                        autoAgencyList[val] = data.isOpen

                        window.localStorage.autoAgencyList = JSON.stringify(autoAgencyList)

                        const str = val.replace('/', '')
                        oAutoWrap.querySelector(`.j-auto-${ str }`).innerHTML = data.isOpen ? str : ''

                        oAutoWrap.title = [...oAutoWrap.children].reduce((init, item) => {
                            init += ` ${ item.innerHTML }`
                            return init
                        }, '')
                    },
                })
            }
                break
            case 'recycle': {
                ajax({
                    url: `${ val }/agency-recycleApi?stemp=${ Date.now() }`,
                    success(data) {
                        showSuccessTip(data.message)
                    },
                })
            }
                break
            case 'refresh': {
                ajax({
                    url: `${ val }/agency-change-refresh`,
                    success(data) {
                        autoRefreshList[val] = data.isOpen

                        window.localStorage.autoRefreshList = JSON.stringify(autoRefreshList)

                        const str = val.replace('/', '')
                        oAutoRefresh.querySelector(`.j-refresh-${ str }`).innerHTML = data.isOpen ? str : ''

                        oAutoRefresh.title = [...oAutoRefresh.children].reduce((init, item) => {
                            init += ` ${ item.innerHTML }`
                            return init
                        }, '')
                    },
                })
            }
                break
            case 'query': {
                const key = keyDom.value
                ajax({
                    url: `${ val }/agency-queryApi`,
                    data: { key },
                    success(data) {
                        let value = '{}'
                        let query = ''
                        let param = ''
                        let extname = ''
                        if (data.success) {
                            const targetData = data.data
                            extname = targetData.extname
                            value = JSON.stringify(JSON.parse(targetData.data), null, extname === 'json' ? 2 : 0)

                            query = Object.keys(targetData.query || {}).length ? JSON.stringify(targetData.query, null, 2) : ''
                            param = targetData.param ? JSON.stringify(JSON.parse(targetData.param), null, 2) : ''
                            targetData.store && (delayDom.value = targetData.store.delay)

                            window.agency4api.show(targetData)
                        } else {
                            showErrorTip('未查询到结果')
                            oMainWrap.querySelector('.j-agency-query-param').value = query
                            oMainWrap.querySelector('.j-agency-param-param').value = param

                            thisJSONEditor.setText(value)
                        }
                    },
                })
            }
                break
            case 'query-config': {
                if (e.altKey) {
                    try {
                        let data = null
                        const dataStr = thisJSONEditor.getText().trim()
                        dataStr && (data = new Function(`return ${ dataStr }`)())

                        if (data) {
                            ajax({
                                type: 'post',
                                url: `${ val }/agency-config-update`,
                                contentType: 'application/json',
                                data: {
                                    data,
                                },
                                success(data) {
                                    showSuccessTip(data.message)
                                },
                            })
                        }
                    } catch (e) {
                        showSuccessTip('data error')
                        return
                    }
                    e.preventDefault()
                } else {
                    ajax({
                        url: `${ val }/agency-config-query`,
                        success(data) {
                            let val = null
                            if (data.success) {
                                val = data.data
                            }

                            thisJSONEditor.setText(val ? JSON.stringify(JSON.parse(val), null, 4) : '{}')
                        },
                    })
                }
            }
                break
            case 'insert': {
                let key = keyDom.value.trim()
                let data, query, param, apiState

                if (!key) {
                    keyDom.classList.add('agency-data-error')
                    keyDom.timer = setTimeout(() => {
                        keyDom.classList.remove('agency-data-error')
                    }, 1000)
                    console.log('输入要新增的url')
                    return
                }

                const fullUrlReArr = /^https?:\/\/[^/]+/.exec(key)
                if (fullUrlReArr) {
                    key = key.replace(fullUrlReArr[0], '')
                }

                key.indexOf('/') === 0 || (key = `/${ key }`)

                if (/\?/.test(key)) {
                    let arr = key.split('?')
                    key = arr[0]

                    arr = arr[1].split('&')
                    const json = {}
                    arr.forEach(item => {
                        if (item) {
                            const [key, value] = item.split('=')
                            json[key] = value
                        }
                    })
                    oMainWrap.querySelector('.j-agency-query-param').value = JSON.stringify(json, null, 2)
                    keyDom.value = key
                }
                try {
                    const dataStr = thisJSONEditor.getText().trim()
                    const queryStr = oMainWrap.querySelector('.j-agency-query-param').value.trim()
                    const paramStr = oMainWrap.querySelector('.j-agency-param-param').value.trim()
                    dataStr && (data = JSON.stringify(new Function(`return ${ dataStr }`)()))
                    queryStr && (query = JSON.stringify(new Function(`return ${ queryStr }`)()))
                    paramStr && (param = JSON.stringify(new Function(`return ${ paramStr }`)()))

                    const agencyPre = `/${ key.split('/')[1] }`
                    if (agency4apiList.includes(agencyPre)) {
                        oMainWrap.querySelector('.j-instance-group').value = agencyPre
                        val = agencyPre
                    } else {
                        key = val + key
                    }
                } catch (e) {
                    console.error('data error')
                    return
                }
                const apiStateStr = oMainWrap.querySelector('.j-apiStatus').value
                apiStateStr && (apiState = apiStateStr)

                ajax({
                    type: 'post',
                    url: `${ val }/agency-createApi`,
                    contentType: 'application/json',
                    data: {
                        key,
                        query,
                        param,
                        data,
                        apiState,
                        store: { delay },
                        pathGroup: oMainWrap.querySelector('.j-agency-path-group').value,
                    },
                    success() {
                        showSuccessTip('创建成功')
                        delayDom.value = ''
                    },
                })
            }
                break
            case 'edit': {
                const key = keyDom.value
                let data
                
                try {
                    const dataStr = thisJSONEditor.getText().trim()
                    data = JSON.stringify(new Function(`return ${ dataStr }`)())
                } catch (e) {
                    console.error('data error')
                    return
                }
                ajax({
                    type: 'post',
                    url: `${ val }/agency-modifyApi`,
                    contentType: 'application/json',
                    data: {
                        key,
                        store: { delay },
                        data,
                    },
                    success() {
                        showSuccessTip('修改成功')
                        delayDom.value = ''
                    },
                })
            }
                break
            case 'delete':
                oDeleteBox.style.display = 'inline-block'
                hideDom(oNormalBtnWrap)
                showDom(oSureDelWrap)
                break
            case 'cancel-delete':
            case 'sure-delete':
                if (eType === 'sure-delete') {
                    const delByUrl = oMainWrap.querySelector('.j-del-by-url')
                    const delByGroup = oMainWrap.querySelector('.j-del-by-group')
                    const clearBox = oMainWrap.querySelector('.j-clear')
                    const clearAllBox = oMainWrap.querySelector('.j-clearAll')

                    {
                        const key = keyDom.value
                        const submitData = {
                            isClearAll: clearAllBox.checked,
                            isClear: clearBox.checked,
                        }
                        if (delByUrl.checked) {
                            submitData.keyPath = key.indexOf('/') === 0 ? key : `/${ key }`
                        } else if (delByGroup.checked) {
                            submitData.pathGroup = oMainWrap.querySelector('.j-agency-path-group').value
                        } else if (!(submitData.isClear || submitData.isClearAll)) {
                            if (key) {
                                submitData.key = key
                            } else {
                                clearTimeout(keyDom.timer)
                                keyDom.classList.add('agency-data-error')
                                keyDom.timer = setTimeout(() => {
                                    keyDom.classList.remove('agency-data-error')
                                }, 1000)
                                console.log('请输入要删除的内容')
                                return
                            }
                        }

                        ajax({
                            type: 'get',
                            url: `${ val }/agency-delApi`,
                            data: submitData,
                            success() {
                                showSuccessTip('删除成功')
                                
                                delByUrl.checked = false
                                clearBox.checked = false
                                clearAllBox.checked = false
                            },
                        });

                        [...oDeleteBox.querySelectorAll('input')].forEach(item => item.checked = false)
                    }
                }

                hideDom(oDeleteBox)
                oNormalBtnWrap.style.display = 'flex'
                hideDom(oSureDelWrap)
                break
            case 'close':
                oMask.onclick()
                break
        }
    }

    oMainWrap.oncontextmenu = function (e) {
        const eType = e.target.getAttribute('e-type')
        const instanceGroup = oMainWrap.querySelector('.j-instance-group')
        const list = [...instanceGroup.options]
        switch (eType) {
            case 'start':
            case 'refresh': {
                const isStart = eType === 'start'
                const targetAction = isStart ? 'agency' : 'refresh'

                const fn = function (val) {
                    ajax({
                        url: `${ val }/agency-change-${ targetAction }`,
                        success(data) {
                            const str = val.replace('/', '')
                            let selector = ''
                            const isOpen = data.isOpen
                            let targetData = null
                            let targetProp = null
                            let dom = null
                            if (isStart) {
                                targetData = autoAgencyList
                                targetProp = 'autoAgencyList'
                                selector = 'auto'
                                dom = oAutoWrap
                            } else {
                                targetData = autoRefreshList
                                targetProp = 'autoRefreshList'
                                selector = 'refresh'
                                dom = oAutoRefresh
                            }
                            targetData[val] = isOpen
                            window.localStorage[targetProp] = JSON.stringify(targetData)

                            dom.querySelector(`.j-${ selector }-${ str }`).innerHTML = isOpen ? str : ''
                        },
                    })
                }
                list.forEach((option) => {
                    fn(option.value)
                })

                e.preventDefault()
            }
                break
        }
    }
    
    {
        const oAgency4apiListDiv = document.createElement('div')
        document.addEventListener('agency4api-show', () => {
            const oTarget = document.querySelector('.agency4api-wrap')
            oTarget.style.left = '0'
            oTarget.style.transform = 'none'
    
            document.body.appendChild(oAgency4apiListDiv)
            oAgency4apiListDiv.style.display = 'block'
            oAgency4apiListDiv.innerHTML = ''
    
            document.querySelector('.ace-jsoneditor').style.fontSize = '30px'
    
            ajax({
                type: 'get',
                url: 'http://localhost:3000/longtest/agency-queryInfoList', 
                data: {
                    number: 100,
                }, 
                success(res) {
                    if (!Object.keys(res.data)?.[0].length) {
                        return
                    }
                    const filePathList = []
                    const idProp = `agency4api-id${ Date.now() }`
                    const sHtml = `
                    <content class="${ idProp }">
                        <span e-type="clear-list" class="${ idProp }-close">清空</span>
                        ${ Object.keys(res.data).map(pathGroup => res.data[pathGroup].map((item, index) => `
                            <div 
                                data-index="${ index }" 
                                data-path-group="${ pathGroup }" 
                                class="${ idProp }-item"
                            >
                                ${ filePathList.push(item.filePath) && item.json.keyPath }
                            </div>
                        `).join('')) }
                    </content>
                    <style>
                    .agency4api-wrap select, .agency4api-wrap textarea, .agency4api-wrap input{
                        font-size: 20px;
                    }
                    .${ idProp }-close{
                        position:absolute;
                        padding: 10px;
                        z-index: 1;
                        right: 5px;
                        top: 5px;
                        cursor: pointer;
                    }
                    .${ idProp }{
                        position: fixed;
                        right: 0;
                        top: 0;
                        padding: 30px 20px 10px;
                        bottom: 0;
                        width: 35%;
                        font-size: 20px;
                        background: white;
                        z-index: 100000000;
                        overflow: auto;
                        cursor: pointer;
                        color: blue;
                    }
                    .${ idProp }-item{
                        word-break: break-all;
                        word-wrap: break-word;
                        padding: 10px 0;
                    }
                    .${ idProp }-item:hover{
                        color: #fff;
                        background: blue;
                    }
                    </style>
                `
                    oAgency4apiListDiv.innerHTML = sHtml
                    oAgency4apiListDiv.onclick = ({ target }) => {
                        const index = target.getAttribute('data-index')
                        const pathGroup = target.getAttribute('data-path-group')
                        if (index) {
                            const json = res.data[pathGroup][index].json
                            window.agency4api.show(json)
                            document.querySelector('.j-agency-key').value = json.keyPath
                        }

                        if (target.getAttribute('e-type') === 'clear-list') {
                            ajax({
                                type: 'post',
                                url: `${ oMainWrap.querySelector('.j-instance-group').value }/agency-delApi`,
                                contentType: 'application/json',
                                data: {
                                    filePathList,
                                },
                                success() {
                                    oAgency4apiListDiv.children[0].innerHTML = ''
                                    showSuccessTip('删除成功')
                                },
                            })
                        }
                    }
                },
            })
        })
        document.addEventListener('agency4api-hide', () => {
            oAgency4apiListDiv.style.display = 'none'
        })
    }
}

// 异步，以免影响主进程
setTimeout(() => {
    document.readyState === 'complete' ? fn() : document.addEventListener('readystatechange', () => {
        if (document.readyState === 'complete') {
            fn()
        }
    })
}, 10)
